#coding=utf-8

from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.forms.util import ErrorList
import re

num_re = re.compile(r'[0-9]+')
field_re = re.compile(r'[\w]+')

class LoginForm(forms.Form):
    username = forms.CharField(error_messages={'required': u'用户名不能为空'},
                               widget=forms.TextInput(attrs={'class': 'input-t'}))
    password = forms.CharField(error_messages={'required': u'密码不能为空'},
                               widget=forms.PasswordInput(render_value=False,
                               attrs={'class': 'input-t'}))
    
    def clean(self):
        if 'username' in self.cleaned_data and 'password' in self.cleaned_data:
            user = authenticate(username=self.cleaned_data['username'],
                                password=self.cleaned_data['password'])
            if user is not None:
                if not user.is_active:
                    self._errors["username"] = ErrorList([u"该用户已停用"])
                    del self.cleaned_data['username']
                    del self.cleaned_data['password']
            else:
                self._errors["username"] = ErrorList([u"用户名或密码错误"])
                del self.cleaned_data['username']
                del self.cleaned_data['password']

        return self.cleaned_data

class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=16, min_length=4,
                               error_messages={'required': u'用户名不能为空',
                                               'max_length': u'用户名的长度为4-16位',
                                               'min_length': u'用户名的长度为4-16位'},
                               widget=forms.TextInput())
    password = forms.CharField(min_length=6, max_length=16,
                               error_messages={'required': u'密码不能为空',
                                               'min_length': u'密码长度至少为6位',
                                               'max_length': u'密码长度最大为16位'},
                               widget=forms.PasswordInput(render_value=False))
    confirm_password = forms.CharField(required=False, max_length=16,
                                       widget=forms.PasswordInput(render_value=False,))
    name = forms.CharField(max_length=32, widget=forms.TextInput(), error_messages={'required':'你到底是谁啊 写名字', 'max_length':'Big Bong! 腾讯可没有这么长的QQ号哦~'})
    email = forms.EmailField(max_length=64, widget=forms.TextInput(),
                             error_messages={'required': u'邮箱不能为空',
                                             'invalid': u'邮箱格式不正确',
                                             'max_length':u'邮箱的最大长度为64位，你丫咋那么长呢？咋那么不小山呢？'})
    qq = forms.CharField(max_length=16, widget=forms.TextInput(), error_messages={'max_length':'Big Bong! 腾讯可没有这么长的QQ号哦~'}, required=False)
    celphone = forms.CharField(max_length=11, min_length=11, required=False, widget=forms.TextInput(),
                                 error_messages={'max_length': u'手机号码只能是11位，你蒙我呢？', 'min_length': u'手机号码只能是11位，你蒙我呢？'})
    student_num = forms.CharField(max_length=8, min_length=8, required=False, widget=forms.TextInput(),
                                 error_messages={'max_length': u'学号只能是8位，你蒙我呢？', 'min_length': u'学号只能是8位，你蒙我呢？'})
    msn = forms.EmailField(max_length=64, widget=forms.TextInput(), required=False,
                           error_messages={'invalid': u'MSN格式不正确',
                                           'max_length':u'MSN的最大长度为64位，你丫要是真的MSN地址又超长，联系管理员去'})
    address = forms.CharField(max_length=128, widget=forms.TextInput(), error_messages={'max_length':'你丫住火星上了？地址这么长？最多128字哦'}, required=False)
    company = forms.CharField(max_length=128, widget=forms.TextInput(), error_messages={'max_length':'你公司老板是饶舌歌手？公司名这么长？最多128字哦'}, required=False)
    remarks = forms.CharField(widget=forms.Textarea(), required=False)

# Username的格式和是否存在的验证
    def clean_username(self):
        value = self.cleaned_data['username']
        
        if not field_re.search(value):
            raise forms.ValidationError(u'用户名格式不正确，只能输入字母，数字，下划线')
        
        user = User.objects.filter(username=value)
        if user:
            raise forms.ValidationError(u'该用户名已存在，请重新输入')
        
        return value

# Email存在验证
    def clean_email(self):
        value = self.cleaned_data['email']
        user = User.objects.filter(email=value)
        if user:
            raise forms.ValidationError(u'该邮箱已存在，请重新输入')
        
        return value
    
# QQ号验证
    def clean_qq(self):
        if 'qq' in self.cleaned_data:
            val = self.cleaned_data['qq']
            if val != '' and num_re.search(val) == None :
                raise forms.ValidationError(u'手机号码格式不正确,只能输入数字')
            return val
    
# 手机号验证
    def clean_celphone(self):
        if 'cell_phone' in self.cleaned_data:
            val = self.cleaned_data['cell_phone']
            if val != '' and num_re.search(val) == None :
                raise forms.ValidationError(u'手机号码格式不正确,只能输入数字')
            return val

# 两次密码相同验证
    def clean(self):
        if ('confirm_password' in self.cleaned_data) and ('password' in self.cleaned_data):
            if (self.cleaned_data['confirm_password'] != self.cleaned_data['password']):
                self._errors["confirm_password"] = ErrorList([u"两次输入密码不匹配"])
                del self.cleaned_data['password']
                del self.cleaned_data['confirm_password']
            
        return self.cleaned_data
